#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mg_TLC59116.h"


//毫秒级延时（非阻塞）
void TLC59116_Delay_Ms(uint32_t ms)
{
	usleep(1000 * ms);
}
//LED芯片GPIO初始化
void TLC59116_GPIO_Init(void)
{
	ithGpioSetMode(TLC59116_RST_Pin, ITH_GPIO_MODE0);
	ithGpioSetOut(TLC59116_RST_Pin);
	ithGpioClear(TLC59116_RST_Pin);
	usleep(10);
	ithGpioSet(TLC59116_RST_Pin);
}
//写寄存器
uint32_t TLC59116WriteReg(uint8_t REG_Address, uint8_t Data)
{
	return I2C0_Write_8Reg(TLC59116_LED_DEVICE_ADDR, REG_Address, &Data, 1);
}
//写多个寄存器
void TLC59116WriteMultiReg(uint8_t Start_REG_Address, uint8_t *dat, uint8_t data_len)
{
	I2C0_Write_8Reg(TLC59116_LED_DEVICE_ADDR, Start_REG_Address, dat, data_len);
}
//EEPROM读一个字节
uint8_t TLC59116ReadReg(uint8_t Start_REG_Address)
{
	return (I2C0_Read_8Reg(TLC59116_LED_DEVICE_ADDR, Start_REG_Address));
}
//复位TLC59116
uint8_t TLC59116Reset(void)
{
	TLC59116WriteReg(0xA5, 0x5A);
}
//LED由组PWM控制
void TLC59116_By_Gpwm(void)
{
	if (TLC59116ReadReg(TLC59116_LEDMODE2) == 0x00)return;
	TLC59116WriteReg(TLC59116_LEDMODE2, 0X00);
}
//LED由闪烁控制
void TLC59116_By_Freq(void)
{
	if (TLC59116ReadReg(TLC59116_LEDMODE2) == 0X20)return;
	TLC59116WriteReg(TLC59116_LEDMODE2, 0X20);
}
//单个SinglePwm设置（0-15,0-255）
void TLC59116SetSinglePWM(uint8_t LedNum, uint8_t duty)
{
	TLC59116WriteReg(TLC59116_LEDPWM0 + LedNum, duty);
}
//所有SinglePwm设置
void TLC59116SetAllPWMSame(uint8_t duty)
{
	uint8_t AllDuty[16];
	memset(AllDuty, duty, sizeof(AllDuty));
	TLC59116WriteMultiReg((0xA0 | TLC59116_LEDPWM0), AllDuty, sizeof(AllDuty));
}
//所有SinglePwm设置(不同值)
void TLC59116SetAllPWM(uint8_t* duty)
{
	TLC59116WriteMultiReg((0xA0 | TLC59116_LEDPWM0), duty, 12);
}
//组PWM设置
void TLC59116SetGroupPWM(uint8_t duty)
{
	TLC59116WriteReg(TLC59116_GRPPWM, duty);
}
//设置LED全开
void TLC59116_All_On(void)
{
	uint8_t dat[4] = {0xFF,0xFF,0xFF,0xFF};
	TLC59116WriteMultiReg((0x80 | TLC59116_LEDOUT0), dat, sizeof(dat));
}
//设置LED全关
void TLC59116_All_Off(void)
{
	uint8_t dat[4] = { 0, 0, 0, 0 };
	TLC59116WriteMultiReg((0x80 | TLC59116_LEDOUT0), dat, sizeof(dat));
}
//控制单个Led
void TLC59116_Set_SingleLed(uint8_t Led_Num, uint8_t PWM)
{
	TLC59116SetSinglePWM(Led_Num, PWM);
}
//RGB测试
void TLC59116_TEST(void)
{
	TLC59116_All_On();
	uint8_t i = 0;
	for (i = 0; i<12; i++)
	{
		TLC59116_Set_SingleLed(i, 0xFF);
		TLC59116_Delay_Ms(40);
	}
	for (i = 0; i<12; i++)
	{
		TLC59116_Set_SingleLed(i, 0);
		TLC59116_Delay_Ms(40);
	}
}
//RGB驱动初始化
uint32_t TLC59116_Init(void)
{
	uint32_t ret = 0xFF;
	printf("Moorgen INFO:Try to init TLC59116.\n");
	TLC59116_GPIO_Init();
	ret = TLC59116WriteReg(TLC59116_LEDMODE1, 0X01);
	TLC59116WriteReg(TLC59116_LEDMODE2, 0X00);
	TLC59116_TEST();
	return ret;
}